package logic.common.team;

import java.util.List;

import logic.common.team.processes.CarrierProcess;
import logic.common.team.processes.ProcessAddEvent;
import logic.common.team.processes.ProcessFinishEvent;
import logic.common.team.processes.ProcessStartEvent;
import logic.common.team.processes.TeamProcessListener;
import logic.ships.carrier.Carrier;
import map.asteroids.AsteroidField;

public class CarrierAction extends TeamAction {
	
	private int pendingCarriers;
	
	public CarrierAction(Team team) {
		super(team);
		
		team.addTeamProcessListener(new TeamProcessListener() {
			@Override
			public void processFinished(ProcessFinishEvent event) {
				if(event.getTeamProcess() instanceof CarrierProcess) pendingCarriers--;
			}
			
			@Override
			public void processStarted(ProcessStartEvent event) {}
			@Override
			public void processAdded(ProcessAddEvent event) {}
		});
	}
	
	@Override
	public void performAction() {
		if(newCarrierNecessary()) {
			team.spendTeamMoney(team.getNewCarrierProperties().getCosts());
			team.addTeamProcess(new CarrierProcess(team));
			pendingCarriers++;
		}
		
		List<AsteroidField> fields = team.getCarrierFreeFields();
		if(fields.isEmpty()) return;
		
		for(Carrier carrier : team.getCarriers()) {
			if(!carrier.arrived() && carrier.getCurrentMoveLocation() == null) {
				AsteroidField nextField = fields.get(0);
				carrier.moveTo(nextField);
			}
		}
	}
	
	private boolean newCarrierNecessary() {
		if(team.getTeamMoney() < team.getNewCarrierProperties().getCosts()) return false;
		
		return team.getCarrierFreeFields().size() > team.getCarriers().size() + pendingCarriers;
	}
}